import { baseUrl, VERSION } from "./config"
import { checkUrl } from "./common"
import { wxToast } from "./wxApi"
export function request(method, url, data, config) {
  const app = getApp()
  var is = true
  if (url == 'do?c=3001') {
    is = false
  }
  let noGymId = true
  let shopId = 1
  if(app) {
    shopId = app.globalData.SHOPID
  }
  if (url == 'do?c=3001' || url == 'do?c=3003' || url == 'do?c=103026') {
    noGymId = false
  }
  return new Promise(resolve => {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    wx.request({
      method,
      url: checkUrl(url) ? url : baseUrl + url,
      data,
      header: {
        'content-type': 'application/json', // 默认值
        shopId,
        version: VERSION,
        Cookie: is ? wx.getStorageSync('cookie') : null,
        gymId: noGymId ? wx.getStorageSync('GYMID') : '',
        userId: wx.getStorageSync('userId'),
      },
      ...config,
      success (res) {
        wx.hideLoading()
        if (url == 'do?c=3001') {   //判断存cookie
          console.log('存cookie', res.cookies[0])
          if (res.cookies && res.cookies.length != 0) {
            console.log('存cookie', res.cookies[0])
            wx.setStorageSync("cookie", res.cookies[0]);
          }
        }
        if (res.data.errorCode === "000000") {    //请求成功后的回调
          if (url == 'do?c=3001' && res.data.record && res.data.record.editPwd =='1') {
            wx.showToast({ title: '长时间未修改密码，请登录后台修改登录密码', icon: 'none', duration: 2000 }) 
          } else if (url == 'do?c=3001' && res.data.record && res.data.record.editPwd =='2') {
            wx.showToast({ title: '当前密码为初始密码，请登录后台修改登录密码', icon: 'none', duration: 2000 }) 
          }
          resolve(res.data || true)
        } else if (res.data.errorCode !== "000000") {
          wx.showToast({ title: res.data.errorMsg || '发生错误', icon: 'none', duration: 2000 })  
          resolve(res.data || false)
          if(res.data.errorCode === '00016'|| res.data.errorCode === '00068') {
            setTimeout(() => {
              wx.removeStorageSync('userId');
              wx.removeStorageSync('nickName');
              wx.navigateTo({
                url: '/pages/login/index'
              })
            }, 500);
          }     
        } 
      },
      fail() {
        wx.hideLoading()
        wxToast('网络错误', 'none')
      }
    })
  })
}

/**
 * get 请求方法
 * @param {string} url 请求地址
 * @param {*} data 请求数据
 */
export function get(url, data, config) {
  return request('GET', url, data, config)
}

/**
 * post 请求方法
 * @param {string} url 请求地址
 * @param {*} data 请求数据
 */
export function post(url, data, config) {
  return request('POST', url, data, config)
}

/**
 * put 请求方法
 * @param {string} url 请求地址
 * @param {*} data 请求数据
 */
export function put(url, data, config) {
  return request('PUT', url, data, config)
}